package com.hzqx.syndata.hzqx.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static org.apache.commons.net.ftp.FTPReply.isPositiveCompletion;

/**
 * 判断ftp文件是否存在
 * @author yinzhiping
 */
@Slf4j
public class ChargeFtpFileIfExistsUtil {

    public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
    }

    public static List<String> getFile(String host, int port, String username, String password, String remotePath, Date lastTime,Date now) {
        long beginTime = System.currentTimeMillis();
        boolean result = false;
        FTPClient ftp = new FTPClient();
        List<String> list = new ArrayList<>();
        //设置超时时间30s
        ftp.setConnectTimeout(30000);
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口，可以使用ftp.connect(host)的方式直接连接FTP服务器
            // 登录
            ftp.login(username, password);
//            try {
//                ftp.setSoTimeout(10000);
//            } catch (SocketException e) {
//                System.out.println("10s未读完--------------");
//                e.printStackTrace();
//            }
            reply = ftp.getReplyCode();
            if (!isPositiveCompletion(reply)) {
                ftp.disconnect();
                log.error("ftp login failed:");
                return new ArrayList<>();
            }

            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode(); //被动模式
            // 转移到FTP服务器目录
            ftp.changeWorkingDirectory(remotePath);
            FTPFile[] fs = ftp.listFiles();
            System.out.println("长度--"+fs.length);
            if(fs.length>0){
                for (FTPFile ff : fs) {
                    String f = new String(ff.getName().getBytes("ISO-8859-1"), "GBK");
                    //utc时间加上时间差
                    Calendar calendar = ff.getTimestamp();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date m = calendar.getTime();
                    //System.out.println(m);
//                    Long addTime = ff.getTimestamp().getTimeInMillis() +
//                            ff.getTimestamp().getTimeZone().getOffset(0);
//                    Date date = new Date(addTime);
                    if(m.getTime()>=lastTime.getTime()&&m.getTime()< now.getTime()){
                        String s = new String(ff.getName().getBytes("ISO-8859-1"),"UTF-8");
                        System.out.println(s);
                        list.add(s);
                    }
                    long end = System.currentTimeMillis();
                    long spend = (end-beginTime);

                    if(spend>20000){
                        throw new RuntimeException();
                    }
//                    if(ff.isFile()&&date.getTime()>lastTime.getTime()){
//                        //System.out.println(ff.getName()+";;;;"+date);
//                        return true;
//                    }
                }
            }
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    log.error("ftp disconnect failed:",ioe);
                }
            }
        }
        return list;
    }


    public static boolean getOutFile(String host, int port, String username, String password, String remotePath, String fileName, OutputStream is) {
        long beginTime = System.currentTimeMillis();
        boolean result = false;
        FTPClient ftp = new FTPClient();
        List<String> list = new ArrayList<>();
        //设置超时时间30s
        ftp.setConnectTimeout(30000);
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口，可以使用ftp.connect(host)的方式直接连接FTP服务器
            // 登录
            ftp.login(username, password);
            reply = ftp.getReplyCode();
            if (!isPositiveCompletion(reply)) {
                ftp.disconnect();
                log.error("ftp login failed:");
                return result;
            }

            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode(); //被动模式
            // 转移到FTP服务器目录
            ftp.changeWorkingDirectory(remotePath);
            FTPFile[] fs = ftp.listFiles();
            if(fs.length>0){
                for (FTPFile ff : fs) {
                    if(fileName.equals(new String(ff.getName().getBytes("ISO-8859-1"),"UTF-8"))){
                        ftp.retrieveFile(ff.getName(), is);
                        is.close();
                    }

                    long end = System.currentTimeMillis();
                    long spend = (end-beginTime);

                    if(spend>20000){
                        throw new RuntimeException();
                    }
                }
            }
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    log.error("ftp disconnect failed:",ioe);
                }
            }
        }
        return result;
    }
}
